<template>
  <div class="management-container">
    <!-- 页面头部 -->
    <div class="header">
      <div class="header-content">
        <div class="header-left">
          <button class="btn-back" @click="goBack">
            <i class="fas fa-arrow-left"></i>
            返回
          </button>
          <div class="header-icon">
            <i class="fas fa-clipboard-list"></i>
          </div>
          <div class="header-text">
            <h1>我的预约</h1>
            <p>一天后将删除未处理预约</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-box">
        <i class="fas fa-search"></i>
        <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索科室、医生姓名或预约号..."
          class="search-input"
          @input="handleSearch"
        >
      </div>
    </div>

    <!-- 预约列表 -->
    <div class="appointments-section">
      <div class="section-title">
        <h2>预约记录</h2>
        <span class="appointment-count">(共 {{ filteredAppointments.length }} 条)</span>
      </div>

      <div class="appointments-list" v-if="filteredAppointments.length > 0">
        <!-- 修复1：v-for 键值用 resId（后端返回的唯一标识，替代未定义的 id） -->
        <div
          class="appointment-card"
          v-for="appointment in filteredAppointments"
          :key="appointment.resId"
        >
          <div class="appointment-header">
            <div class="appointment-id">
              <i class="fas fa-hashtag"></i>
              预约号: {{ appointment.resId }}
            </div>
            <!-- 修复2：状态类名绑定（保持原有逻辑，兼容 resolve 空值） -->
            <div class="appointment-status" :class="`status-badge ${
              appointment.resolve === 0 ? 'pending' :
              appointment.resolve === 1 ? 'confirmed' :
              appointment.resolve === 2 ? 'completed' :
              appointment.resolve === 3 ? 'cancelled' :
              appointment.resolve === 4 ? 'not-prescribed' :
              appointment.resolve === 5 ? 'completed' : 'pending'
            }`">
              {{ getStatusText(appointment.resolve) }}
            </div>
          </div>

          <div class="appointment-body">
            <div class="appointment-info">
              <div class="info-item">
                <div class="info-label">
                  <i class="fas fa-user"></i>
                  患者:
                </div>
                <div class="info-value">{{ appointment.name }}</div>
              </div>
              <div class="info-item">
                <div class="info-label">
                  <i class="fas fa-stethoscope"></i>
                  科室:
                </div>
                <div class="info-value">{{ appointment.department }}</div>
              </div>
              <div class="info-item">
                <div class="info-label">
                  <i class="fas fa-user-md"></i>
                  医生:
                </div>
                <div class="info-value">{{ appointment.doctor }}</div>
              </div>
              <div class="info-item">
                <div class="info-label">
                  <i class="fas fa-calendar-alt"></i>
                  预约时间:
                </div>
                <!-- 修复3：用后端返回的 datetime 格式化（替代未定义的 appointmentTime） -->
                <div class="info-value">{{ formatDateTime(appointment.datetime) }}</div>
              </div>
            </div>

            <div class="appointment-actions">
              <button
                class="btn-view"
                @click="viewAppointmentDetails(appointment)"
              >
                <i class="fas fa-eye"></i>
                查看详情
              </button>
              <!-- 修复4：取消按钮添加禁用逻辑（已处理/已取消不可点击），避免误操作报错 -->
              <button
                class="btn-cancel"
                @click="cancelAppointment(appointment)"
                :disabled="appointment.resolve === 1 || appointment.resolve === 3 || appointment.resolve === 2 || appointment.resolve === 5"
                :title="appointment.resolve === 1 ? '已处理不可取消' :
                        appointment.resolve === 3 ? '已取消不可重复操作' :
                        appointment.resolve === 2 ? '已完成不可取消' :
                        appointment.resolve === 5 ? '已完成不可取消' : '取消预约'"
              >
                <i class="fas fa-times"></i>
                取消预约
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else>
        <div class="empty-icon">
          <i class="fas fa-calendar-times"></i>
        </div>
        <h3 v-if="searchQuery.trim()">未找到匹配的预约记录</h3>
        <h3 v-else>暂无预约记录</h3>
        <p v-if="searchQuery.trim()">请尝试其他搜索关键词</p>
        <p v-else>您还没有任何预约记录</p>
      </div>
    </div>

    <!-- 预约详情模态框 -->
    <div class="modal-overlay" v-if="showAppointmentDetails && selectedAppointment">
      <div class="modal-content">
        <div class="modal-header">
          <h2 class="modal-title">预约详情</h2>
          <button type="button" class="btn-close" @click="showAppointmentDetails = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="appointment-details">
            <div class="detail-section">
              <h3>基本信息</h3>
              <div class="detail-item">
                <div class="detail-label">预约号:</div>
                <div class="detail-value">{{ selectedAppointment.resId }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">患者姓名:</div>
                <div class="detail-value">{{ selectedAppointment.name }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">身份证号:</div>
                <div class="detail-value">{{ selectedAppointment.identity }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">手机号码:</div>
                <div class="detail-value">{{ selectedAppointment.phone }}</div>
              </div>
            </div>

            <div class="detail-section">
              <h3>就诊信息</h3>
              <div class="detail-item">
                <div class="detail-label">就诊科室:</div>
                <div class="detail-value">{{ selectedAppointment.department }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">预约医生:</div>
                <div class="detail-value">{{ selectedAppointment.doctor }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">预约时间:</div>
                <div class="detail-value">{{ formatDateTime(selectedAppointment.datetime) }}</div>
              </div>
              <div class="detail-item">
                <div class="detail-label">预约状态:</div>
                <div class="detail-value">
                  <span class="status-badge" :class="`status-badge ${
                    selectedAppointment.resolve === 0 ? 'pending' :
                    selectedAppointment.resolve === 1 ? 'confirmed' :
                    selectedAppointment.resolve === 2 ? 'completed' :
                    selectedAppointment.resolve === 3 ? 'cancelled' :
                    selectedAppointment.resolve === 4 ? 'not-prescribed' :
                    selectedAppointment.resolve === 5 ? 'completed' : 'pending'
                  }`">
                    {{ getStatusText(selectedAppointment.resolve) }}
                  </span>
                </div>
              </div>
            </div>

            <!-- 修复5：用后端返回的 queryIs 字段判断问卷状态（替代未定义的 questionnaireCompleted） -->
            <div class="detail-section">
              <h3>健康问卷</h3>
              <div class="questionnaire-summary">
                <p>
                  <i class="fas fa-clipboard-check"></i>
                  {{ selectedAppointment.queryIs === 1 ? '患者已填写健康问卷' : '患者未填写健康问卷' }}
                </p>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn-close-modal" @click="showAppointmentDetails = false">
            关闭
          </button>
          <!-- 修复6：模态框取消按钮同样添加禁用逻辑 -->
          <button
            type="button"
            class="btn-cancel-modal"
            @click="cancelAppointment(selectedAppointment)"
            :disabled="selectedAppointment.resolve !== 0"
          >
            <i class="fas fa-times"></i>
            取消预约
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request';
const router = useRouter()

// 响应式数据（保持原有）
const appointments = ref([])
const searchQuery = ref('')
const showAppointmentDetails = ref(false)
const selectedAppointment = ref(null)
const loading = ref(false)

// 一、Token 处理（保持原有）
const getTokenFromCookie = () => {
  const cookies = document.cookie.split('; ');
  for (const cookie of cookies) {
    const [name, value] = cookie.split('=');
    if (name === 'Admin-Token') {
      return decodeURIComponent(value);
    }
  }
  return null;
};

// 请求头（保持原有）
const requestHeaders = computed(() => ({
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${getTokenFromCookie()}`,
  'X-Requested-With': 'XMLHttpRequest'
}));

// 二、状态文本转换（保持原有）
const getStatusText = (resolve) => {
  switch(resolve) {
    case 0: return '待处理';
    case 1: return '已下发';
    case 2: return '已处理';
    case 3: return '已取消';
    case 4: return '未开药';
    case 5: return '已完成';
    default: return '未知状态';
  }
};

// 三、处理搜索输入（保持原有）
const handleSearch = () => {
  console.log('搜索关键词:', searchQuery.value)
}

// 四、搜索功能（保持原有）
const filteredAppointments = computed(() => {
  if (!searchQuery.value.trim()) {
    return appointments.value
  }
  const query = searchQuery.value.trim().toLowerCase()
  return appointments.value.filter(app => {
    const departmentName = (app.department || '').toLowerCase()
    const doctorName = (app.doctor || '').toLowerCase()
    const patientName = (app.name || '').toLowerCase()
    const appointmentId = (app.resId || '').toLowerCase()
    return (
      departmentName.includes(query) ||
      doctorName.includes(query) ||
      patientName.includes(query) ||
      appointmentId.includes(query)
    )
  })
})

// 五、加载预约数据（保持原有，确保字段完整）
const loadAppointments = async () => {
  loading.value = true;
  try {
    // 直接使用封装的 request，自动处理 Token、路径前缀、响应解析
    const response = await request({
      url: '/reservation/my', // 自动拼接 VITE_APP_BASE_API 前缀
      method: 'GET'
    });

    // 无需手动解析 JSON/判断状态码（request.js 已统一处理）
    appointments.value = (response.data || []).map(app => ({
      resId: app.resId || '未知编号',
      name: app.name || '未知患者',
      identity: app.identity || '未填写',
      phone: app.phone || '未填写',
      department: app.department || '未知科室',
      doctor: app.doctor || '未知医生',
      resolve: app.resolve ?? 0,
      datetime: app.appointmentDate || '未知时间',
      queryIs: app.queryIs ?? 0,
    }));

  } catch (error) {
    console.error('加载预约异常:', error);
    alert(error.message || '加载预约失败，请重试');
    appointments.value = [];
  } finally {
    loading.value = false;
  }
};

// 六、日期时间格式化（修复：仅接收一个参数，适配后端 datetime 字段）
const formatDateTime = (dateString) => {
  try {
    // 处理后端返回的时间格式（如 "2025-11-19T14:30:00" 或 "2025-11-19 14:30:00"）
    const date = new Date(dateString.replace('T', ' '));
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    return '时间格式错误';
  }
}

// 七、查看详情（保持原有）
const viewAppointmentDetails = (appointment) => {
  selectedAppointment.value = appointment
  showAppointmentDetails.value = true
}

// 八、取消预约（保持原有逻辑，已处理/已取消状态会拦截）
const cancelAppointment = async (appointment) => {
  if (!appointment) return;

  // 已处理（2）/已取消（3）状态，禁止取消
  if ([2, 3, 4, 5].includes(appointment.resolve)) {
    alert(getStatusText(appointment.resolve) + '，不可取消');
    return;
  }

  if (confirm(`确定要取消预约 ${appointment.resId} 吗？`)) {
    try {
      const token = getTokenFromCookie();
      if (!token) {
        alert('登录态已失效，请重新登录！');
        window.location.href = '/login';
        return;
      }

      // 仅修复：替换硬编码的/dev-api为环境变量，适配生产环境
      const response = await fetch(`${import.meta.env.VITE_APP_BASE_API}/reservation/cancel/${appointment.resId}`, {
        method: 'POST',
        headers: requestHeaders.value,
        credentials: 'include'
      });

      // 检查响应是否为JSON格式
      const contentType = response.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        throw new Error('服务器响应不是有效的JSON格式，可能未登录或接口异常');
      }

      if (!response.ok) throw new Error('取消预约失败');

      const result = await response.json();
      if (result.code !== 200) throw new Error(result.msg || '取消预约失败');

      alert('取消预约成功');
      loadAppointments(); // 重新加载列表
      showAppointmentDetails.value = false;

    } catch (error) {
      console.error('取消预约出错:', error);
      alert(error.message || '取消预约失败，请重试');
    }
  }
}

// 九、返回上一页（保持原有）
const goBack = () => {
  router.back()
}

// 十、生命周期（保持原有）
onMounted(() => {
  loadAppointments()
})
</script>

<style scoped>
.management-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #2c3e50, #34495e);
  color: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.btn-back {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  font-size: 16px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 20px;
}

.btn-back:hover {
  background: rgba(255, 255, 255, 0.3);
}

.btn-back i {
  margin-right: 8px;
}

.header-icon {
  font-size: 32px;
  margin-right: 15px;
  color: #3498db;
}

.header-text h1 {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 5px 0;
}

.header-text p {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
}

/* 搜索区域 */
.search-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-box {
  position: relative;
  max-width: 500px;
}

.search-box i {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #777;
}

.search-input {
  width: 100%;
  padding: 15px 15px 15px 45px;
  font-size: 18px;
  border: 2px solid #e0e0e0;
  border-radius: 10px;
  transition: all 0.3s;
}

.search-input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
  outline: none;
}

/* 预约列表部分 */
.appointments-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title h2 {
  font-size: 22px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0;
}

.appointment-count {
  font-size: 16px;
  color: #7f8c8d;
  margin-left: 10px;
}

/* 预约卡片样式 */
.appointments-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.appointment-card {
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s;
}

.appointment-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.appointment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
}

.appointment-id {
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
}

.appointment-id i {
  margin-right: 8px;
  color: #3498db;
}

.appointment-status {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
}

.appointment-status.pending {
  background: #fff3cd;
  color: #856404;
}

.appointment-status.confirmed {
  background: #d1ecf1;
  color: #0c5460;
}

.appointment-status.cancelled {
  background: #f8d7da;
  color: #721c24;
}

.appointment-status.completed {
  background: #d4edda;
  color: #155724;
}

.appointment-status.not-prescribed {
  background: #f8d7da;
  color: #721c24;
}

.appointment-body {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 15px;
}

.appointment-info {
  flex: 1;
}

.info-item {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.info-label {
  min-width: 80px;
  font-weight: 600;
  color: #555;
  display: flex;
  align-items: center;
}

.info-label i {
  margin-right: 8px;
  width: 16px;
  text-align: center;
  color: #3498db;
}

.info-value {
  color: #333;
}

.appointment-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  min-width: 100px;
}

.btn-view {
  padding: 10px 15px;
  font-size: 14px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.btn-view:hover {
  background: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.btn-cancel {
  padding: 10px 15px;
  font-size: 14px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.btn-cancel:hover {
  background: #c0392b;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.btn-cancel:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.btn-cancel:disabled:hover {
  background: #bdc3c7;
  transform: none;
  box-shadow: none;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-state .empty-icon {
  font-size: 60px;
  color: #ddd;
  margin-bottom: 15px;
}

.empty-state h3 {
  font-size: 20px;
  color: #666;
  margin-bottom: 10px;
}

.empty-state p {
  font-size: 16px;
  color: #777;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  max-width: 600px;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title {
  font-size: 22px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0;
}

.btn-close {
  background: none;
  border: none;
  font-size: 20px;
  color: #777;
  cursor: pointer;
  padding: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.btn-close:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 15px;
}

/* 详情样式 */
.appointment-details {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h3 {
  font-size: 18px;
  color: #2c3e50;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e0e0e0;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
}

.detail-label {
  min-width: 100px;
  font-weight: 600;
  color: #555;
}

.detail-value {
  color: #333;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
}

.status-badge.pending {
  background: #fff3cd;
  color: #856404;
}

.status-badge.confirmed {
  background: #d1ecf1;
  color: #0c5460;
}

.status-badge.cancelled {
  background: #f8d7da;
  color: #721c24;
}

.status-badge.completed {
  background: #d4edda;
  color: #155724;
}

.status-badge.not-prescribed {
  background: #f8d7da;
  color: #721c24;
}

.questionnaire-summary {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  text-align: center;
}

.questionnaire-summary p {
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.btn-close-modal {
  background: #95a5a6;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-close-modal:hover {
  background: #7f8c8d;
}

.btn-cancel-modal {
  background: #e74c3c;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-cancel-modal:hover {
  background: #c0392b;
}

.btn-cancel-modal:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.btn-cancel-modal:disabled:hover {
  background: #bdc3c7;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .management-container {
    padding: 15px;
  }

  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .header-left {
    flex-direction: column;
    align-items: flex-start;
    width: 100%;
  }

  .btn-back {
    align-self: flex-start;
    margin-bottom: 15px;
  }

  .appointment-body {
    flex-direction: column;
  }

  .appointment-actions {
    flex-direction: row;
    width: 100%;
  }

  .btn-view, .btn-cancel {
    flex: 1;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .info-label {
    min-width: auto;
    margin-bottom: 5px;
  }

  .detail-item {
    flex-direction: column;
  }

  .detail-label {
    min-width: auto;
    margin-bottom: 5px;
  }

  .modal-footer {
    flex-direction: column;
  }

  .modal-footer button {
    width: 100%;
  }
}
</style>